package 网络编程项目.login.utiles;


import org.apache.commons.lang3.StringUtils;
import 网络编程项目.login.entity.User;
import 网络编程项目.pojo.Message;
import 网络编程项目.pojo.Response;
import 网络编程项目.pojo.ResponseType;
import 网络编程项目.util.ObjectUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;


public class LoginUtil {
  public static volatile Map<String, SelectionKey> OnlineUser = new Hashtable<>();

  //登录用户
  public static void login(SelectionKey key, Message message) throws IOException {
    //将客户端的用户转换成Object对象
    User user = JsonUtil.StringToUser(message.getMsg());
    //判断是否是正确的用户
    Response response = new Response();
    if (isOurUser(user)) {
      response.setType(ResponseType.IS_TRUE_USER);
      User u = sqlUtil.getUserByID(user.getUserid());
      response.setMsg(JsonUtil.UserToString(u));

      sendResponse(key, response);

      OnlineUser.put(u.getUsername(), key);
    } else {
      response.setType(ResponseType.IS_FALSE_USER);
      sendResponse(key, response);
    }
  }

  //注册用户
  public static boolean register(Message message) {
    boolean bool = false;
    try {
      User user = JsonUtil.StringToUser(message.getMsg());
      bool = sqlUtil.insertUser(user);
    } catch (Exception ignored) {
    }
    return bool;
  }

  //判断是否有重复的ID
  public static boolean findID(Message message) {
    User u = JsonUtil.StringToUser(message.getMsg());
    String id = u.getUserid();
    User user = sqlUtil.getUserByID(id);
    return !StringUtils.isEmpty(user.getUserid());
  }

  //判断是否登录成功
  public static boolean isOurUser(User user) {
    User u = sqlUtil.getUserByID(user.getUserid());
    if (StringUtils.isEmpty(u.getUserid())) {
      return false;
    }
    if (StringUtils.isEmpty(user.getPassword())) {
      return false;
    }
    return user.getPassword().equals(u.getPassword());
  }

  //给特定的客户端发送消息
  public static void sendResponse(SelectionKey key, Response response) throws IOException {
    byte[] str = ObjectUtils.serialize(response);
    try {
      SocketChannel channel = (SocketChannel) key.channel();
      ByteBuffer buffer = ByteBuffer.wrap(str);
      channel.write(buffer);
    } catch (IOException ignored) {
    }
  }

  //获取客户端发送的消息
  public static Message getMessage(SelectionKey key) {
    Message message = new Message();
    SocketChannel channel = null;
    try {
      channel = (SocketChannel) key.channel();
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      int len = channel.read(buffer);
      buffer.flip();
      String str = new String(buffer.array(), 0, len);
      if (str.contains("message")) {
        message = JsonUtil.StringToMessage(str);
      }
    } catch (IOException e) {
      try {
        key.cancel();
        channel.close();
      } catch (IOException ignored) {
      }
    }
    return message;
  }
}
